<template>
  <div class="flex ht100 flex-v pd-15 box-border">
    <div class="header">
      <span>{{$route.meta.title}}</span>
    </div>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="ruleForm.title"></el-input>
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input v-model="ruleForm.author"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="order">
        <el-input v-model="ruleForm.order"></el-input>
      </el-form-item>
      <el-form-item label="文章栏目" prop="menuId">
        <el-select v-model="ruleForm.menuId" placeholder="请选择文章栏目" @change="menuChange">
          <el-option  :label="item.name" :value="item.id" :key="item.id" v-for="item in menu">{{item.name}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="封面"  prop="cover">
        <el-upload
          class="banner-upload"
          :action="Api.uploadUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :headers="{'nochat-token':$store.state.auth.token}"
          :data="{'path':'/'+$store.state.auth.wechatId+'/banners/','attr':'cover','type':'single'}"
          :before-upload="beforeAvatarUpload">
          <img v-if="ruleForm.cover" :src="ruleForm.cover" class="banner-upload-img">
          <i v-else class="el-icon-plus banner-upload-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="内容"  prop="content">
        <quill-editor v-model="ruleForm.content"
                      ref="myQuillEditor">
        </quill-editor>

      </el-form-item>
      <template v-if="expand && expand!='null'" v-for="(item,expandIndex) in expand">
        <el-form-item  :label="item[1]"  :prop="'attr'+(expandIndex+1)">
          <quill-editor v-if="item[0]==='html'" v-model="ruleForm['attr'+(expandIndex+1)]"
                        ref="myQuillEditor">
          </quill-editor>
          <el-input v-if="item[0]==='string'"  v-model="ruleForm['attr'+(expandIndex+1)]"></el-input>
          <el-upload v-if="item[0]==='image'"
            class="banner-upload"
            :action="Api.uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
                     :http-request="uploadImg"
            :headers="{'nochat-token':$store.state.auth.token}"
            :data="{'path':'/'+$store.state.auth.wechatId+'/article/','attr':'attr'+(expandIndex+1),'type':'single'}"
            :before-upload="beforeAvatarUpload">
            <img v-if="ruleForm['attr'+(expandIndex+1)]" :src="ruleForm['attr'+(expandIndex+1)]" class="banner-upload-img">
            <i v-else class="el-icon-plus banner-upload-icon"></i>
          </el-upload>

          <div v-if="item[0]==='images'">
            <el-upload v-for="(img,imgIndex) in ruleForm['attr'+(expandIndex+1)]"
                       class="banner-upload"
                       :action="Api.uploadUrl"
                       :show-file-list="false"
                       :on-success="handleAvatarSuccess"
                       :http-request="uploadImg"
                       :headers="{'nochat-token':$store.state.auth.token}"
                       :data="{'path':'/'+$store.state.auth.wechatId+'/article/','attr':'attr'+(expandIndex+1),'type':'range','index':imgIndex}"
                       :before-upload="beforeAvatarUpload">
              <img v-if="ruleForm['attr'+(expandIndex+1)][imgIndex]!==''" :src="ruleForm['attr'+(expandIndex+1)][imgIndex]" class="banner-upload-img">
              <i v-else class="el-icon-plus banner-upload-icon"></i>
            </el-upload>
          </div>

          <div v-if="item[0]==='model'">
            <el-select v-model="ruleForm['attr'+(expandIndex+1)]" multiple placeholder="请选择">
              <el-option
                v-for="item in brand"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div v-if="item[0]==='select'">
            <el-select v-model="ruleForm['attr'+(expandIndex+1)]" placeholder="请选择">
              <el-option
                v-for="option in tag"
                :key="option.id"
                v-if="option.classId===item[2]"
                :label="option.name"
                :value="option.name">
              </el-option>
            </el-select>
          </div>
        </el-form-item>
      </template>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
  import { quillEditor } from 'vue-quill-editor'
  export default {
    data () {
      return {
        ruleForm: {
          title: '',
          link: '',
          cover: '',
          author:'',
          content:'',
          attr1:'',
          attr2:'',
          attr3:'',
          attr4:'',
          attr5:'',
          attr6:'',
          attr7:'',
          attr8:'',
          attr9:'',
          attr10:'',
          attr11:'',
          attr12:'',
          attr13:'',
          attr14:'',
          attr15:'',
          attr16:'',
          attr17:'',
        },
        rules: {
          title: [
            { required: true, message: '请输入海报名称', trigger: 'blur' }
          ]
        },
        menu:[],
        brand:[],
        expand:[]
      }
    },
    components: {
      quillEditor
    },
    methods:{
      handleAvatarSuccess(res, file,fileList,event) {
          debugger;
        this.ruleForm.cover = res.path;
      },
      uploadImg:function (event) {

        console.log(event);
        var formData=new FormData();
        formData.append("file",event.file);
        formData.append("path",event.data.path);
        console.log(formData);
        this.Api.uploadImag(formData).then((res)=>{
          if(event.data.type=='single'){
            this.ruleForm[event.data.attr]=res.data.path;
          }else{
            this.ruleForm[event.data.attr][event.data.index]=res.data.path;
            this.$set(this.ruleForm[event.data.attr],event.data.index,res.data.path);
            console.log(this.ruleForm[event.data.attr],[event.data.index],res.data.path);
          }
        })
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;


        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return  isLt2M;
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            for(let i=0;i<this.menu.length;i++){
              if(this.menu[i].expand){
                for(let u=0;u<this.menu[i].expand.length;u++){
                  if(this.menu[i].expand[u][0]=='images' || this.menu[i].expand[u][0]=='model'){
                    this.ruleForm['attr'+(u+1)]=JSON.stringify(this.ruleForm['attr'+(u+1)]);
                  }
                }
              }
            }
            if(this.ruleForm.id){//update
              this.Api.updateArticle(this.ruleForm).then((response)=>{
                this.$message.success(response.data.message);
                this.$router.push({
                  name:'appArticleIndex'
                })
              })
            }else{//create
              this.Api.createArticle(this.ruleForm).then((response)=>{
                this.$message.success(response.data.message);
                this.$router.push({
                  name:'appArticleIndex'
                })
              })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      imgHandler(state) {
        this.addRange = this.$refs.myQuillEditor.quill.getSelection();
        if (state) {
          let fileInput = document.getElementById('imgInput');
          fileInput.click() // 加一个触发事件
        }
        this.uploadType = 'image'
      },
      menuChange(value){
        let menuId=value;
        var index;
        for(var i =0;i<this.menu.length;i++){
          if(this.menu[i].id==menuId){
              index=i;
              break;
          }
        }
        this.expand=this.menu[index].expand;
        this.getMenu(this.pageParams).then(()=>{
          if(this.$route.query.id){
            this.Api.getArticleDetail(this.$route.query.id).then((res)=>{
              this.ruleForm=res.data;
              for(let i=0;i<this.menu.length;i++){
                if(this.menu[i].expand){
                  for(let u=0;u<this.menu[i].expand.length;u++){
                    if(this.menu[i].expand[u][0]=='images' || this.menu[i].expand[u][0]=='model'){
                      this.ruleForm['attr'+(u+1)]=eval(this.ruleForm['attr'+(u+1)]);
                    }
                  }
                }
              }
//              this.menuChange(this.ruleForm.menuId);
            })
          }else{
            for(let i=0;i<this.menu.length;i++){
              if(this.menu[i].expand){
                for(let u=0;u<this.menu[i].expand.length;u++){
                  if(this.menu[i].expand[u][0]=='images'){
                    if(!this.ruleForm['attr'+(u+1)]){
                      this.ruleForm['attr'+(u+1)]=[];
                      for(var m=0;m<this.menu[i].expand[u][2];m++){
                        this.ruleForm['attr'+(u+1)][m]="";
                      }
                    }
                  }else if(this.menu[i].expand[u][0]=='model'){
                    this.ruleForm['attr'+(u+1)]=[];
                  }
                }
              }
            }
            console.log(this.ruleForm);
          }
        })

      },
      getMenu:function (pageParams) {
        return new Promise((resolve,reject)=>{
          this.Api.getMenu({pageParams:pageParams}).then((res)=>{
            this.menu=res.data.data;
            for(let i=0;i<this.menu.length;i++){
              this.menu[i].expand=JSON.parse(this.menu[i].expand);
            }
            resolve();
          });
        })
      }
    },
    mounted(){
      let _pageParams=JSON.parse(JSON.stringify(this.$store.state.auth.pageParams));
      _pageParams.pageLimit=100;
      this.Api.getBrand({pageParams:_pageParams}).then((res)=>{
          this.brand=res.data.data;
      })
      let _pageParams1=JSON.parse(JSON.stringify(this.$store.state.auth.pageParams));
      _pageParams1.where.classId=1;
      this.Api.getTag(_pageParams1).then((res)=>{
          this.tag=res.data.data;
      })
//      let _pageParams2=JSON.parse(JSON.stringify(this.$store.state.auth.pageParams));
//      _pageParams2.where.classId=2;
//      this.Api.getTag(_pageParams2).then((res)=>{
//        this.type=res.data.data;
//      })
//      let _pageParams3=JSON.parse(JSON.stringify(this.$store.state.auth.pageParams));
//      _pageParams3.where.classId=3;
//      this.Api.getTag(_pageParams3).then((res)=>{
//        this.scale=res.data.data;
//      })
      this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler);
      this.pageParams=this.$store.state.auth.pageParams;

      this.getMenu(this.pageParams).then(()=>{
        if(this.$route.query.id){
          this.Api.getArticleDetail(this.$route.query.id).then((res)=>{
            this.ruleForm=res.data;
            for(let i=0;i<this.menu.length;i++){
              if(this.menu[i].expand){
                for(let u=0;u<this.menu[i].expand.length;u++){
                  if(this.menu[i].expand[u][0]=='images' || this.menu[i].expand[u][0]=='model'){
                    this.ruleForm['attr'+(u+1)]=eval(this.ruleForm['attr'+(u+1)]);
                  }
                }
              }
            }
            this.menuChange(this.ruleForm.menuId);
          })
        }
      })

    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>

  .header{
    border-bottom: 1px solid #eee;
    margin-bottom: 10px;
    padding-bottom: 10px;
  }
  .header span{
    line-height: 40px;
    font-size: 20px;
  }

  .banner-upload-img {
    width: 200px;
    height: auto;
    display: block;
  }
  .banner-upload .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .banner-upload .el-upload:hover {
    border-color: #409EFF;
  }
  .banner-upload-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .ql-container{
    height: 500px;
  }
</style>
